import { request } from '@umijs/max';
import moment from "moment";

export function getAuthHeader() {
  let authHeader = {};
  const accessToken = localStorage.getItem('ACCESS_TOKEN');
  if (accessToken) {
    const token = JSON.parse(accessToken);
    authHeader = { Authorization: `Bearer ${token.accessToken}` };
  }
  return authHeader;
}

export async function download(url: string, params: any, filename: string) {
  const response = await request<any>(url, {
    headers: getAuthHeader(),
    method: 'GET',
    params,
    responseType: 'blob',
  });
  const a = document.createElement('a');
  a.href = window.URL.createObjectURL(response);
  a.download = `${filename}-${moment().format('YYYYMMDDHHmmss')}.xlsx`;
  a.click();
  window.URL.revokeObjectURL(response);
}

export function getImageUploadUrlAndName(filePath: string, filename?: string) {
  return `${API_URL}/api/upload?filepath=${filePath}&filename=${filename}`;
}

export function getImageUploadUrl(filePath: string) {
  const filename = '';
  return `${API_URL}/api/upload?filepath=${filePath}&filename=${filename}`;
}

export function getImageUploadUrlToLocal() {
  return `${API_URL}/api/upload/local`;
}

export function getUploadUrl(relativePath: string) {
  return `${API_URL}/api/${
    relativePath.startsWith('/') ? relativePath.replace('/', '') : relativePath
  }`;
}

export function getEditorUploadUrl() {
  const konsoleToken = localStorage.getItem('konsole-token');
  if (konsoleToken) {
    const token = JSON.parse(konsoleToken);
    return `${API_URL}/api/upload/editor?accessToken=${token.accessToken}`;
  }
  return undefined;
}
